package hxy.dragon.config.security;

import hxy.dragon.dao.model.UserModel;
import hxy.dragon.service.UserService;
import hxy.dragon.util.JwtUtil;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.Collections;

/**
 * JWT authentication filter
 *
 * @author houxiaoyi
 */
@Slf4j
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    @Lazy
    private UserService userService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {

        // Always process JWT if present, regardless of existing authentication
        final String authorizationHeader = request.getHeader("Authorization");

        String username = null;
        String jwt = null;

        // Extract JWT from Authorization header
        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
            jwt = authorizationHeader.substring(7);
        } else {
            // Fallback: try cookie AUTH_TOKEN for template-based navigation
            Cookie[] cookies = request.getCookies();
            if (cookies != null) {
                for (Cookie c : cookies) {
                    if ("AUTH_TOKEN".equals(c.getName())) {
                        jwt = c.getValue();
                        break;
                    }
                }
            }
        }

        // If JWT token is present, validate and set authentication
        if (jwt != null) {
            try {
                username = jwtUtil.extractUsername(jwt);

                // Validate token
                if (jwtUtil.validateAccessToken(jwt, username)) {
                    // Get user from database
                    UserModel user = userService.findByUsernameOrEmail(username);
                    if (user != null && user.getEnabled()) {
                        UsernamePasswordAuthenticationToken authToken =
                                new UsernamePasswordAuthenticationToken(
                                        username,
                                        null,
                                        Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER"))
                                );
                        SecurityContextHolder.getContext().setAuthentication(authToken);
                    } else {
                        log.error("当前用户不存在 {}", username);
                    }
                }
            } catch (RuntimeException e) {
                log.warn("Error extracting username from JWT", e);
            } catch (Exception e) {
                log.error("Error extracting username from JWT", e);
            }
        }

        filterChain.doFilter(request, response);
    }
}